<script>
import MessageArea from '@/components/MessageArea'
import { getMessage, postMessage } from '@/api/message';
import { debounce } from '@/utils/debounce';
export default {

  components: {
    MessageArea,
  },
  data() {
    return {
      data: null,
      isLoading: true,

      page: 1,
    }
  },
  computed: {
    list() {
      return this.data.rows
    },
    total() {
      return this.data.total
    },
  },
  methods: {
    handSubmit(messageInfo, callback) {
      this.isLoading = true;
      const message = {
        nickname: messageInfo.inputArea,
        content: messageInfo.textArea,
      }
      postMessage(message).then((resp) => {
        this.data.rows.unshift(resp.data)
        this.data.total++
        this.isLoading = false
        callback('评论成功')
      })
    },

    handScroll() {
      this.$bus.$emit('mainScroll', this.$refs.container)
    },
    handSetMainScroll(scrollNum) {
      this.$refs.container.scrollTop = scrollNum
    },

    getMoreMessage(dom) {
      const MaxMessage = 100
      if (this.isLoading || this.data.rows.length >= MaxMessage) {
        return;
      }
      const totalHeight = dom.clientHeight
      const scrollTop = dom.scrollTop
      const scrollHeight = dom.scrollHeight
      const gap = scrollHeight - totalHeight - scrollTop
      if (gap < 100) {
        this.isLoading = true
        this.page++
        getMessage(this.page).then((resp) => {
          this.data.rows = [
            ...this.data.rows,
            ...resp.data.rows,
          ]
          this.isLoading = false;
        })
      }
    }
  },
  created() {
    getMessage().then((resp) => {
      this.data = resp.data;
      this.isLoading = false;
    })
  },
  mounted() {
    this.$refs.container.addEventListener('scroll', this.handScroll)
    this.$bus.$on('setMainScroll', this.handSetMainScroll)
    this.$bus.$on('mainScroll', debounce(this.getMoreMessage, 50))
  },
  beforeDestroy() {
    this.$bus.$emit('mainScroll')
    this.$bus.$off('setMainScroll', this.handSetMainScroll)
    this.$refs.container.removeEventListener('scroll', this.handScroll)
  },

}
</script>



<template>
  <div class="message-container" ref="container" v-loading="isLoading">
    <div class="container">
      <MessageArea v-if="data" @submit="handSubmit" :list="list" :isListLoading="isLoading" title="留言列表"
        :subTitle='`(${total})`' />
    </div>
  </div>
</template>



<style lang='less' scoped>
.message-container {
  width: 100%;
  height: 100%;
  overflow-y: scroll;


  .container {
    width: 60%;
    margin: 50px auto;
  }
}
</style>